package com.jz.community.basecomm.net.retrofit;

import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.utils.JsonUtils;
import com.jz.community.basecomm.utils.Preconditions;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.HttpException;

/**
 * Created by Tony.Fan on 2018/6/15 16:45
 * <p>
 * 异常处理
 */
public class ApiException {

    public static final int UNAUTHORIZED = 401;
    public static final int FORBIDDEN = 403;
    public static final int NOT_FOUND = 404;
    public static final int REQUEST_TIMEOUT = 408;
    public static final int INTERNAL_SERVER_ERROR = 500;
    public static final int BAD_GATEWAY = 502;
    public static final int SERVICE_UNAVAILABLE = 503;
    public static final int GATEWAY_TIMEOUT = 504;
    public static final int FAIL_CODE_409 = 409;

    private static String bodyString = "";

    public static ResponseThrowable handleException(Throwable e) {
        ResponseThrowable ex;
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            ResponseBody body = ((HttpException) e).response().errorBody();
            try {
                if (!Preconditions.isNullOrEmpty(body)) {
                    bodyString = body.string();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            ex = new ResponseThrowable(e, httpException.code());
            switch (httpException.code()) {
                case UNAUTHORIZED:
                case FORBIDDEN:
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case GATEWAY_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                default:
                    if (!Preconditions.isNullOrEmpty(bodyString)) {
                        BaseResponseInfo baseResponseInfo = JsonUtils.parseObject(bodyString, BaseResponseInfo.class);
                        if (!Preconditions.isNullOrEmpty(baseResponseInfo)){
                            ex.message = baseResponseInfo.getMessage();
                        }
                    } else {
                        ex.message = "未知错误";
                    }
                    break;
            }
            return ex;
        } else {
            ex = new ResponseThrowable(e);
            return ex;
        }
    }

    public static class ResponseThrowable extends IOException {
        public int code;
        public String message;

        public ResponseThrowable(Throwable throwable) {
            super(throwable);
        }

        public ResponseThrowable(Throwable throwable, int code) {
            super(throwable);
            this.code = code;
        }

        public ResponseThrowable(String message, int code) {
            this.code = code;
            this.message = message;
        }
    }
}
